package com.leiou.stu_list;

import com.google.gson.Gson;
import com.leiou.pojo.Student;
import com.leiou.utils.CommonResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/*
 *蒋碧鹏
 *
 */
@WebServlet("/allStu")
public class StulistHandler extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        StulistDao stulistDao = new StulistDaoImpl();
        String page = req.getParameter("page");
        String size = req.getParameter("size");
        if (page == null || size == null) {
            resp.getWriter().write(new Gson().toJson(CommonResult.fail(400, "缺少分页参数page或size")));
            return;
        }
        int ipage = Integer.parseInt(page);
        int isize = Integer.parseInt(size);
        List<Student> allStudents = stulistDao.findAllstus(ipage, isize);
        if (allStudents == null) {
            resp.getWriter().write(new Gson().toJson(CommonResult.fail(500, "数据库查询失败")));
            return;
        }
        Gson gson = new Gson();

        CommonResult<List<Student>> temp = null;
        if (allStudents.size() > 0) {
            temp = CommonResult.success(allStudents);
        } else {
            temp = CommonResult.fail(500, "没有学生数据");
        }
        String s = gson.toJson(temp);
        System.out.println(">>>>>>>>>>." + s);
        resp.getWriter().write(s);
    }
}
